import { NewBingServer, IBingInfoPartial } from "./server/index.js"
import { NewBingSocket, sendConversationMessage } from "./socket/index.js"
import { config } from "./config.js"
import ProxyAgent from "proxy-agent"
import { parentPort } from "worker_threads";

const { proxyUrl } = config// 代理地址
const agent = ProxyAgent(proxyUrl)// 访问vpn代理地址
// 初始化bing请求
const bingServer = new NewBingServer({
    agent
})
// 初始化bing的websocket消息
const bingSocket = new NewBingSocket({
    address: "/sydney/ChatHub",
    options: {
        agent
    }
})
let invocationId = -1// 同一段对话的id
let bingInfo: IBingInfoPartial// bing的conversation信息，BingServer请求的结果
const startBingConversation = async () => {
    initEvent()
    await initBingServer()
    initBingSocket()
}

const initEvent = () => {
    bingServer.on("new-bing:server:error", (...args) => { throw new Error(...args) })// 请求抛错
    bingSocket.on("new-bing:socket:error", (...args) => { throw new Error(...args) })// 消息抛错
    // 接收主线程的消息
    parentPort.on("message", (res) => {
        const { type } = res
        if (type === "sendMessage") {
            // 发送消息
            sendConversationMessage.call(bingSocket, { message: res.message, invocationId: ++invocationId })
        }
    })
}
const initBingServer = async () => {
    await bingServer.reset()// 重置请求
    bingInfo = bingServer.bingInfo
}
const initBingSocket = () => {
    bingSocket.mixBingInfo(bingInfo).createWs().initEvent().on("init:finish", () => {// socket初始化完成
        parentPort.postMessage({
            type: "init:finish"
        })
    }).on("message:finish", (data = "") => {
        // 一段对话完成
        parentPort.postMessage({
            type: "message:finish",
            data
        })
    }).on("message:ing", (data = "") => {
        // 对话时，触发主线程loading操作
        parentPort.postMessage({
            type: "message:ing",
            data
        })
    })
}

startBingConversation()